'use strict';

define([
  'angular',
  'angularAMD',
  'angular-cookies'
], function(ng, angularAMD) {

  angularAMD.controller('homeCtrl', ['$scope', '$http','ngDialog', '$location', '$timeout', '$cookies',
    function($scope, $http, ngDialog,$location, $timeout, $cookies) {
    	var mainSlider,adBanner1,adBanner2,initSwiperFlag;
      var hasMore = true,page = 1,limit = 6;

      $scope.need_scroll = false;

      var $w = $(window);
      $w.unbind("scroll");
     // deleteProduct(1);
     // var is_receive = 1;
      var is_receive = $cookies.get('is_receive');
      // if (is_receive=="1") {
      //   console.log(11)
      // }

      $scope.is_receive = is_receive;

      $scope.sendcoupon = function(){
        var customer_id = $cookies.get('customer_id');
        var submitData = {};
        submitData.is_receive = is_receive;
        submitData.customer_id = customer_id;
        
        $http.post('index.php?route=feed/rest_api/sendcoupon',submitData).then(function(result) {
          // console.log(result.data);
          // console.log(result.data;
          $scope.is_receive = result.data.is_receive;
          $cookies.putObject('is_receive', result.data.is_receive, { path: '/' });
          
          $location.path("/pages/introduce");
        })
      }

    	$http.get("index.php?route=feed/rest_api/homepage").then(
          function(result) {
            if (result.data.success !== false) {
              $scope.home = result.data;
              var home_products_page = $cookies.get('home_products_page');
              // var home_scroll_position = $cookies.get('home_scroll_position');
              // if(!isNaN(home_scroll_position)) {
              //   $scope.need_scroll = true;
              // }
              if(home_products_page) {
                $scope.home.products.data = new Array();
                var params = {};
                params.limit = home_products_page*limit;
                params.page = 1;
                $scope.need_scroll = true;
                loadMoreProducts(params);
                page = home_products_page;
              }

              $w.bind("scroll", function(){
                if($("#LoadingProductPlace").length>0 && $w.scrollTop()+$w.height() > $("#LoadingProductPlace").offset().top && hasMore){
                  var params = {limit:limit,page:page};
                  $cookies.put('home_products_page', page, { path: '/' });
                  loadMoreProducts(params);
                }

                if($("#LoadingProductPlace").length>0){
                  if($w.scrollTop()>100){
                    $cookies.put('home_scroll_position', $w.scrollTop(), { path: '/' });
                  }
                }
              });

            }
          }
      )
      


      $scope.gotoCategoryOrProduct = function(sliderItem){
        if(sliderItem.product_id){
          $location.url("/product/"+sliderItem.product_id);
        }else if(sliderItem.category_id){
          $location.url('/categories').search({category_id:sliderItem.category_id});
        }
      }



    	$scope.initSwiper = function() {
    		if(!initSwiperFlag){
    			initSwiperFlag = true;
	        $timeout(function() {
	          mainSlider = new Swiper('#MainSlider', {
	            loop: true,
	            spaceBetween: 0,
	            pagination: '#MainSwiperPagination',
	            paginationClickable: true,
					    autoplay: 4000
	          });
	          adBanner1 = new Swiper('#AdBanner1Slider', {
	            loop: true,
	            spaceBetween: 0,
	            pagination: '#AdBanner1SwiperPagination',
	            paginationClickable: true,
					    autoplay: 4000
	          });
	          adBanner2 = new Swiper('#AdBanner2Slider', {
	            loop: true,
	            spaceBetween: 0,
	            pagination: '#AdBanner2SwiperPagination',
	            paginationClickable: true,
					    autoplay: 4000
	          });
	        })
    		}
      }

      function loadMoreProducts(searchParams) {
        if($scope.loading){
          return;
        }
        var baseUrl = "index.php?route=feed/rest_api/products&simple=1";
        for(var key in searchParams){
          if(searchParams[key]){
            baseUrl += "&"+key+"="+searchParams[key];
          }
        }
        var myuser_id = $cookies.get('myuser_id');

        $scope.myuserId = myuser_id;
        $scope.loading = true;
        $http.get(baseUrl).then(
            function(result) {
              $scope.loading = false;
              page++;
              if (result.data.success) {
                if(result.data.data.length == 0){
                  hasMore = false;
                  $scope.withoutMore = true;
                  return;
                }
                if(!$scope.home.products.data){
                  $scope.home.products.data = new Array();
                }
                angular.forEach(result.data.data,function(productItem){
                  $scope.home.products.data.push(productItem);
                })

                if($scope.need_scroll) {
                  setTimeout(function() {
                    var home_scroll_position = $cookies.get('home_scroll_position');
                    $(window).scrollTop(home_scroll_position);
                  }, 500);
                  $cookies.remove('home_products_page', { path: '/' });
                  // $cookies.remove('home_scroll_position', { path: '/' });
                  $scope.need_scroll = false;
                }

              }else{
                $scope.home.products.data = new Array();
              }
            },function(error){
              $scope.loading = false;
            }
          )
      }

      $scope.gotoCategory = function(category_id){
        if(category_id){
          $location.url('/categories').search({category_id:category_id});
        }
      }

      $scope.gotoProducts = function(category_id){
        if(category_id){
          $location.url('/products').search({category:category_id});
        }
      }
      $scope.initCartByHistoryAtHomePage = function(){
        $location.path("/autopurchase");
        /*
        $http.get('index.php?route=rest/cart/initCartByHistory').then(function(result){
          if (result.data && result.data.success){
            $location.path("/cart");
          }
        })
        */
      }

    }
  ]);

  angularAMD.directive('onNgRepeatEnd', function ($timeout) {
    return {
      restrict: 'A',
      link: function($scope, element, attr) {
        if ($scope.$last == true) {
          $timeout(function() {
            $scope.$eval(attr.onNgRepeatEnd);
          });
        }
      }
    };
  });

});
